import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:yt_devops/components/app_bar/app_bar_widget.dart';
import 'package:yt_devops/components/card_wrap.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/yt_form_text.dart';
import 'package:yt_devops/pages/devices/device_tab/basic_info/setting/bwt_setting.dart';
import 'package:yt_devops/pages/devices/device_tab/basic_info/setting/rect100w_setting.dart';
import 'package:yt_devops/pages/devices/device_tab/basic_info/setting/setting_form/setting_form_widget.dart';
import 'package:yt_devops/pages/devices/device_tab/components/fix_title_width_input.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/func_utils.dart';
import 'basic_info_controller.dart';

/**
 * 其他设备（没有参数设置）共用的基础信息页面
 */

class BasicInfoPage extends GetWidget<BasicInfoController> {
  final int deviceId;
  const BasicInfoPage(this.deviceId, {Key? key}) : super(key: key);
  @override
  BasicInfoController get controller => Get.put(BasicInfoController());
  // BrnFormItemConfig theme = BrnFormItemConfig(
  //     disableTextStyle:
  //         BrnTextStyle(color: Colour.mainTextColor, fontSize: 14.sp),
  //     contentTextStyle:
  //         BrnTextStyle(fontSize: 14.sp, color: Colour.mainTextColor),
  //     titlePaddingLg: const EdgeInsets.only(left: 0),
  //     titleTextStyle:
  //         BrnTextStyle(fontSize: 14.sp, color: Colour.otherTextColor),
  //     formPadding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 13.h));

  @override
  Widget build(BuildContext context) {
    return GetBuilder<BasicInfoController>(
      initState: (state) {
        controller.deviceId = deviceId;
      },
      builder: (controller) => Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBarWidget.withMorePopMenu(
          controller.title,
          context,
          controller.actionKey,
          data: controller.popList,
          onItemClick: (index, value) async {
            if (value == 0) {
              await controller.toAudit();
            } else if (value == 1) {
              Future.delayed(const Duration(milliseconds: 500), () {
                showSettingDialog(context);
              });
            } else {
              Future.delayed(const Duration(milliseconds: 500), () {
                showProductSettingDialog(context);
              });
            }
            return false;
          },
        ),
        body: CardWrap(
          child: ListView.separated(
            shrinkWrap: true,
            padding: EdgeInsets.symmetric(
              horizontal: 16.w,
            ),
            physics: const NeverScrollableScrollPhysics(),
            itemCount: controller.infos.length,
            itemBuilder: (context, index) {
              var item = controller.infos[index];
              return BrnBaseTitle(
                title: item.label,
                themeData: BrnFormItemConfig(
                  disableTextStyle: BrnTextStyle(
                      color: Colour.mainTextColor, fontSize: 14.sp),
                  contentTextStyle: BrnTextStyle(
                      fontSize: 14.sp, color: Colour.mainTextColor),
                  titlePaddingLg: const EdgeInsets.only(left: 0),
                  titleTextStyle: BrnTextStyle(
                      fontSize: 14.sp, color: Colour.otherTextColor),
                  formPadding:
                      EdgeInsets.symmetric(horizontal: 0, vertical: 13),
                ),
                customActionWidget: SizedBox(
                  width: 200.w,
                  child: Text(
                    FuncUtils.isEmpty(item.extraText)
                        ? item.value
                        : '${item.value}(${item.extraText})',
                    style: TextStyles.f14,
                    overflow: TextOverflow.ellipsis,
                    textAlign: TextAlign.end,
                    maxLines: 2,
                  ),
                ),
              );
            },
            separatorBuilder: (BuildContext context, int index) {
              return Gaps.line;
            },
          ),
        ),
      ),
    );
  }

  showSettingDialog(BuildContext context) {
    var paramConfigType = controller.device?.paramConfigType;
    switch (paramConfigType) {
      case 1:
        showMqqtSet(context);
        break;
      case 2:
        showMetterSet(context);
        break;
      case 4:
        showIntervertSet(context);
        break;

      case 7:
        showVoltageAndCurentSet(context);
        break;
      case 5:
      case 8:
        var bwt = BwtSetting(controller.device!.productId!);
        var rect = Rect100WSetting(controller.device!.productId!);
        BrnDialogManager.showConfirmDialog(
          context,
          cancel: ResKey.cancel.tr,
          confirm: ResKey.sure.tr,
          title: ResKey.parameterSets.tr,
          themeData: BrnDialogConfig(dialogWidth: 300.w),
          messageWidget: Container(
              padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12),
              constraints: BoxConstraints(maxHeight: 308.h),
              child: SettingFormWidget(
                key: controller.settingFormKey,
                formData: controller.paramConfig,
                model: paramConfigType == 8 ? bwt.form : rect.form,
              )),
          onCancel: () => Get.back(),
          onConfirm: () async {
            if (controller.settingFormKey.currentState?.validate() == true) {
              var data = controller.settingFormKey.currentState?.save();
              await controller.configCommuniactionInfo(
                data ?? {},
                context,
              );
            }
          },
        );
        break;
      default:
    }
  }

  showProductSettingDialog(BuildContext context) {
    var productConfigType = controller.device?.productConfigType;
    if (productConfigType == 0) {
      showAssociatEMutliDevicesSet(context);
    }
  }

  showVoltageAndCurentSet(BuildContext context) {
    var currentController = TextEditingController();
    var voltageController = TextEditingController();

    currentController.text = controller.device?.config?.currentRatio ?? '';
    voltageController.text = controller.device?.config?.voltageRatio ?? '';
    BrnDialogManager.showConfirmDialog(
      context,
      cancel: ResKey.cancel.tr,
      confirm: ResKey.sure.tr,
      title: ResKey.parameterSets.tr,
      barrierDismissible: false,
      messageWidget: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Center(
          child: SingleChildScrollView(
            // 键盘出现页面自适应
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
              child: Form(
                key: controller.formKey,
                child: Column(children: [
                  FixTitleWidthInput(
                    title: ResKey.currentRatio.tr,
                    controller: currentController,
                    textInputType:
                        const TextInputType.numberWithOptions(decimal: true),
                  ),
                  SizedBox(
                    height: 12.h,
                  ),
                  FixTitleWidthInput(
                    title: ResKey.voltageRatio.tr,
                    controller: voltageController,
                    textInputType:
                        const TextInputType.numberWithOptions(decimal: true),
                  ),
                ]),
              ),
            ),
          ),
        ),
      ),
      onCancel: () {
        Get.back();
      },
      onConfirm: () => controller.setVoltageAndCurent(context, {
        'currentRatio': currentController.text,
        'voltageRatio': voltageController.text
      }),
    );
  }

  // 配置mqtt 用户名和密码
  showMqqtSet(BuildContext context) {
    controller.nameController.text = controller.device?.config?.userName ?? '';
    controller.pwdController.text = controller.device?.config?.password ?? '';
    BrnDialogManager.showConfirmDialog(
      context,
      cancel: ResKey.cancel.tr,
      confirm: ResKey.sure.tr,
      title: ResKey.parameterSets.tr,
      barrierDismissible: false,
      messageWidget: Container(
          padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
          child: Form(
            key: controller.formKey,
            child: Column(children: [
              FixTitleWidthInput(
                title: 'mqtt ${ResKey.userName.tr}',
                controller: controller.nameController,
              ),
              SizedBox(
                height: 12.h,
              ),
              FixTitleWidthInput(
                title: 'mqtt ${ResKey.userPwd.tr}',
                controller: controller.pwdController,
              ),
            ]),
          )),
      onCancel: () => controller.closeForm(),
      onConfirm: () => controller.setMqtt(context),
    );
  }

  // 电表配置
  showMetterSet(BuildContext context) {
    controller.nameController.text = controller.device?.config?.userName ?? '';
    controller.pwdController.text = controller.device?.config?.password ?? '';
    controller.currentController.text =
        controller.device?.config?.currentRatio ?? '';
    controller.voltageController.text =
        controller.device?.config?.voltageRatio ?? '';
    controller.electricController.text =
        controller.device?.config?.energyRatio ?? '';
    controller.poweController.text =
        controller.device?.config?.powerRatio ?? '';

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => BrnDialog(
          actionsText: [ResKey.cancel.tr, ResKey.sure.tr],
          titleText: ResKey.parameterSets.tr,
          contentWidget: SingleChildScrollView(
            padding: EdgeInsets.only(
                bottom: MediaQuery.of(context).viewInsets.bottom / 2),
            child: Container(
              padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 12.h),
              child: Form(
                key: controller.formKey,
                child: Column(children: [
                  FixTitleWidthInput(
                    title: 'mqtt ${ResKey.userName.tr}',
                    controller: controller.nameController,
                  ),
                  FixTitleWidthInput(
                    title: 'mqtt ${ResKey.userPwd.tr}',
                    controller: controller.pwdController,
                  ),
                  FixTitleWidthInput(
                    title: ResKey.currentRatio.tr,
                    textInputType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: controller.currentController,
                  ),
                  FixTitleWidthInput(
                    title: ResKey.voltageRatio.tr,
                    textInputType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: controller.voltageController,
                  ),
                  FixTitleWidthInput(
                    title: ResKey.electricRatio.tr,
                    textInputType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: controller.electricController,
                  ),
                  FixTitleWidthInput(
                    title: ResKey.powerRatio.tr,
                    textInputType:
                        const TextInputType.numberWithOptions(decimal: true),
                    controller: controller.poweController,
                  ),
                ]),
              ),
            ),
          ),
          indexedActionCallback: (index) {
            if (index == 0) {
              controller.closeForm();
            }
            if (index == 1) {
              controller.setMeter(context);
            }
          },
        ),
      ),
    );
  }

  // 逆变器配置
  showIntervertSet(BuildContext context) {
    BrnDialogManager.showConfirmDialog(
      context,
      cancel: ResKey.cancel.tr,
      confirm: ResKey.sure.tr,
      title: ResKey.parameterSets.tr,
      messageWidget: GetBuilder<BasicInfoController>(
        builder: (controller) => Container(
            alignment: Alignment.centerLeft,
            margin: EdgeInsets.fromLTRB(24.w, 16.h, 24.w, 0),
            decoration: const BoxDecoration(
                border: Border(bottom: BorderSide(color: Colour.dividerColor))),
            child: Form(
                key: controller.formKey,
                child: BrnTextSelectFormItem(
                  title: ResKey.thirdPartySite.tr,
                  value: controller.thirdSite?['siteName'] ?? '',
                  themeData: BrnFormItemConfig(
                      tipsTextStyle: BrnTextStyle.withStyle(TextStyles.f14)),
                  onTap: () => controller.toSelectSite(context),
                ))),
      ),
      onCancel: () => controller.closeForm(),
      onConfirm: () => controller.setIntervert(context),
    );
  }

  showAssociatEMutliDevicesSet(BuildContext context) async {
    await controller.getAssociateDevice();
    BrnDialogManager.showConfirmDialog(
      Get.context!,
      cancel: ResKey.cancel.tr,
      confirm: ResKey.sure.tr,
      title: ResKey.parameterSets.tr,
      barrierDismissible: false,
      messageWidget: GetBuilder<BasicInfoController>(
        builder: (controller) => Container(
          child: Column(
            children: [
              Container(
                margin: EdgeInsets.fromLTRB(24.w, 16.h, 24.w, 0),
                child: BrnTextSelectFormItem(
                  title: ResKey.deviceAssociatedDevice.tr,
                  hint: ResKey.pleSelect.tr,
                  themeData: BrnFormItemConfig(
                      titleTextStyle: BrnTextStyle.withStyle(TextStyles.f16),
                      hintTextStyle: BrnTextStyle.withStyle(TextStyles.lf14)),
                  onTap: controller.toSelectDevice,
                ),
              ),
              BrnDeleteTag(
                controller: controller.deleteTagController,
                onTagDelete: (List<String> tags, String? tag, int index) {
                  controller.curSelectDevice.removeAt(index);
                },
              )
            ],
          ),
        ),
      ),
      onCancel: () {
        Get.back();
        controller.curSelectDevice.clear();
        controller.deleteTagController.clear();
      },
      onConfirm: controller.associateDevice,
    );
  }
}
